package com.rybbaby.tss.platform.sysPreserve.controller;

import java.net.UnknownHostException;
import java.text.DecimalFormat;

import com.rybbaby.tss.core.annotation.RequestLog;
import com.rybbaby.tss.core.utils.FileUtils;
import com.rybbaby.tss.core.utils.ServiceInfoUtil;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;


/**
 * @author 谢进伟
 * @description 服务器监控
 * @createDate 2017/3/7 15:19
 */
@Controller
@RequestMapping(value = "preserve/service")
public class ServiceController {

	@RequestLog(content = "服务器相关信息")
	@RequestMapping(value = "info")
	public ModelAndView info() {
		ModelAndView mav = new ModelAndView("sysPage/platform/SysPreserve/serviceInfo.html");
		ServiceInfoUtil si = new ServiceInfoUtil();
		try {
			// System信息，从jvm获取
			mav.addObject("systemInfo", si.property());
			//JVM相关信息
			Runtime r = Runtime.getRuntime();
			Double freeMemory = r.freeMemory() * 1D;//剩余空间
			Double totalMemory = r.totalMemory() * 1D;//可用总空间
			Double useMemory = totalMemory - freeMemory;//已使用空间
			Double usageRate = useMemory / totalMemory;
			DecimalFormat df = new DecimalFormat("0.00");
			mav.addObject("jvmFreeMemory", FileUtils.convertFileSize(freeMemory));
			mav.addObject("jvmTotalMemory", FileUtils.convertFileSize(totalMemory));
			mav.addObject("jvmUsageRate", Double.parseDouble(df.format(usageRate)) * 100);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		try {
			// cpu信息
			mav.addObject("cpuInfo", si.cpu());
		} catch (SigarException e) {
			e.printStackTrace();
		}
		try {
			//内存信息
			Sigar sigar = new Sigar();
			Mem mem = sigar.getMem();
			long free = mem.getFree();//剩余
			Double total = mem.getTotal() * 1D;//总内存
			Double used = mem.getUsed() * 1D;//已使用
			Double usageRate = used / total;
			DecimalFormat df = new DecimalFormat("0.00");
			mav.addObject("memFreeMemory", FileUtils.convertFileSize(free));
			mav.addObject("memTotalMemory", FileUtils.convertFileSize(total));
			mav.addObject("memUsageRate", Double.parseDouble(df.format(usageRate)) * 100);
			mav.addObject("memoryInfo", si.memory());
		} catch (SigarException e) {
			e.printStackTrace();
		}
		try {
			// 操作系统信息
			mav.addObject("osInfo", si.os());
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			// 用户信息
			mav.addObject("whoInfo", si.who());
		} catch (SigarException e) {
			e.printStackTrace();
		}
		try {
			// 文件系统信息
			mav.addObject("fileInfo", si.file());
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			// 网络信息
			mav.addObject("netInfo", si.net());
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			// 以太网信息
			mav.addObject("ethernetInfo", si.ethernet());
		} catch (SigarException e) {
			e.printStackTrace();
		}
		return mav;
	}
}
